package com.huashi.dealer.core.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * 密码工具类
 * 参考PHP项目中的密码加密和工具函数
 *
 * @author 谭陈强
 * @since 2025-07-30
 */
public class PasswordUtil {

    /**
     * 密码加密盐值
     * 参考PHP: 'yoshop_salt_SmTRx'
     */
    private static final String PASSWORD_SALT = "yoshop_salt_SmTRx";

    /**
     * Token生成盐值
     * 参考PHP: 'token_salt'
     */
    private static final String TOKEN_SALT = "token_salt";

    /**
     * 密码加密函数
     * 参考PHP: function yoshop_hash($password) { return md5(md5($password) . 'yoshop_salt_SmTRx'); }
     *
     * @param password 原始密码
     * @return 加密后的密码
     */
    public static String yoshopHash(String password) {
        try {
            // 第一次MD5加密
            String firstMd5 = md5(password);
            // 第二次MD5加密（加上盐值）
            return md5(firstMd5 + PASSWORD_SALT);
        } catch (Exception e) {
            throw new RuntimeException("密码加密失败", e);
        }
    }

    /**
     * MD5加密
     *
     * @param input 输入字符串
     * @return MD5加密结果
     */
    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }

    /**
     * 生成GUID
     * 参考PHP: function getGuidV4($trim = true)
     *
     * @param trim 是否去除花括号
     * @return GUID字符串
     */
    public static String getGuidV4(boolean trim) {
        String guid = UUID.randomUUID().toString();
        return trim ? guid : "{" + guid + "}";
    }

    /**
     * 生成GUID（默认去除花括号）
     *
     * @return GUID字符串
     */
    public static String getGuidV4() {
        return getGuidV4(true);
    }

    /**
     * 生成Token
     * 参考PHP: private function token($openid) {
     *     $wxapp_id = self::$wxapp_id;
     *     $guid = \getGuidV4();
     *     $timeStamp = microtime(true);
     *     $salt = 'token_salt';
     *     return md5("{$wxapp_id}_{$timeStamp}_{$openid}_{$guid}_{$salt}");
     * }
     *
     * @param wxappId 小程序ID
     * @param account 用户账号
     * @return 生成的Token
     */
    public static String generateToken(String wxappId, String account) {
        String guid = getGuidV4();
        long timestamp = System.currentTimeMillis();
        String combined = wxappId + "_" + timestamp + "_" + account + "_" + guid + "_" + TOKEN_SALT;
        return md5(combined);
    }

    /**
     * 生成随机验证码
     * 参考PHP: function generateRandomCode($length = 4) {
     *     $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
     *     $code = '';
     *     for ($i = 0; $i < $length; $i++) {
     *         $code .= $characters[rand(0, strlen($characters) - 1)];
     *     }
     *     return $code;
     * }
     *
     * @param length 验证码长度
     * @return 随机验证码
     */
    public static String generateRandomCode(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        StringBuilder code = new StringBuilder();
        
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * characters.length());
            code.append(characters.charAt(index));
        }
        
        return code.toString();
    }

    /**
     * 生成4位随机验证码
     *
     * @return 4位随机验证码
     */
    public static String generateRandomCode() {
        return generateRandomCode(4);
    }
} 